##阅读量工具
import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from .models import ReadNum, ReadDetall
from django.db.models import Sum


def read_statistics_once_read(request, obj):
    """
       ##如果cookie不存在获取的键执行加一操作 若存在则不加一，阅读数不变。
    """
    ct = ContentType.objects.get_for_model(obj)
    key = "%s_%s_read" % (ct.model, obj.pk)
    if not request.COOKIES.get(key):
        '''
        if ReadNum.objects.filter(content_type=ct, object_id=obj.pk).count():
            # 存在记录
            readnum = ReadNum.objects.get(content_type=ct, object_id=obj.pk)

        else:
            # 不存在对应关系 创建对应的记录
            readnum = ReadNum(content_type=ct, object_id=obj.pk)
        '''
        ##上面的if判断等同于↓
        readnum, created = ReadNum.objects.get_or_create(content_type=ct, object_id=obj.pk)

        # 计数加一
        readnum.read_num += 1
        readnum.save()
        ##每天的阅读量
        date = timezone.now()
        '''
        #筛选如果有记录取出来，不存在则创建
        if ReadDetall.objects.filter(content_type=ct,object_id=obj.pk,date=date).count():
            readDetall = ReadDetall.objects.get(content_type=ct,object_id=obj.pk,date=date)
        else:
            readDetall = ReadDetall(content_type=ct,object_id=obj.pk,date=date)
        '''
        ##上面的if判断等同于↓
        readDetall, created = ReadDetall.objects.get_or_create(content_type=ct, object_id=obj.pk, date=date)
        readDetall.read_num += 1
        readDetall.save()

    return key
    # blog.readed_num += 1
    # blog.save()


def get_seven_days_read_data(content_type):
    today = timezone.now().date()
    read_nums = []
    dates = []
    # days = 1 日期差量
    for i in range(7, 0, -1):
        date = today - datetime.timedelta(days=i)
        dates.append(date.strftime('%m/%d'))
        #筛选查询，条件是时间
        read_details = ReadDetall.objects.filter(content_type=content_type,date=date)
        #数据库聚合查询Sum('字段名')
        result = read_details.aggregate(read_num_sum = Sum('read_num'))
        read_nums.append(result['read_num_sum'] or 0)
    return dates,read_nums

##热门数据
def get_today_hot_data(content_type):
    today = timezone.now().date()
    # 筛选排序
    read_details = ReadDetall.objects.filter(content_type=content_type, date=today).order_by('-read_num')
    ##切片取前七条
    return read_details[:7]

##错误中。。。
def get_yesterday_hot_data(content_type):
    today = timezone.now().date()
    yesterday = today - datetime.timedelta(days=1)##days应等于1...报错未解决
    # 筛选排序
    read_details = ReadDetall.objects.filter(content_type=content_type, date=yesterday).order_by('-read_num')

    return read_details[:7]












'''
#因为数据模型是一对一
if ReadNum.objects.filter(blog = blog).count():
    #存在记录
    readnum = ReadNum.objects.get(blog=blog)

else:
    #不存在对应关系 创建对应的记录
    readnum = ReadNum(blog = blog)

#计数加一
readnum.read_num += 1
readnum.save()
'''
